package cn.jieruoda.eb.system;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.jieruoda.eb.system.domain.entity.SystemAdmin;
import cn.jieruoda.eb.system.domain.repository.SystemAdminRepository;
import cn.jieruoda.eb.system.dto.LoginRequest;
import cn.jieruoda.eb.system.dto.MenusResponse;
import cn.jieruoda.eb.system.service.AdminLoginService;
import cn.jieruoda.eb.system.service.MenuService;
import lombok.RequiredArgsConstructor;

import java.util.Date;

import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

/**
 * 登录测试
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/admin")
public class AdminController {

    final MenuService menuService;
    final AdminLoginService adminLoginService;
    final SystemAdminRepository systemAdminRepository;

    @RequestMapping("login")
    public SaResult doLogin(@RequestBody LoginRequest request) {
        return adminLoginService.doLogin(request);
    }

    @RequestMapping("status")
    public SaResult status() {
        if (StpUtil.isLogin()) {
            return SaResult.ok("login success");
        }
        return SaResult.error().setCode(HttpStatus.UNAUTHORIZED.value());
    }

    @RequestMapping("token")
    public SaResult tokenInfo() {
        return SaResult.data(StpUtil.getTokenInfo());
    }

    @RequestMapping("logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }

    @GetMapping("menus")
    public MenusResponse menus() {

        return menuService.initMenus();
    }

    @GetMapping("list")
    public SaResult list(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        // StpUtil.checkPermission("sys:admin:list");
        return SaResult.data(systemAdminRepository.findAll(PageRequest.of(page, size)));
    }

    @PostMapping("create")
    public SaResult create(@RequestBody SystemAdmin admin) {
        // StpUtil.checkPermission("sys:admin:create");
        admin.setPassword(SaSecureUtil.sha256(SaSecureUtil.md5(admin.getPassword())));
        admin.setCreateTime(new Date());
        admin.setLevel(1);
        admin.setStatus(1);
        admin.setCreateTime(new Date());
        admin.setLastTime(new Date());
        admin.setLastIp("");
        systemAdminRepository.save(admin);
        return SaResult.ok("创建成功");
    }

    @PutMapping("{id}")
    public SaResult update(@PathVariable Integer id, @RequestBody SystemAdmin admin) {
        // StpUtil.checkPermission("sys:admin:update");
        SystemAdmin existingAdmin = systemAdminRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("管理员不存在"));
        
        if (admin.getPassword() != null && !admin.getPassword().isEmpty()) {
            admin.setPassword(SaSecureUtil.sha256(SaSecureUtil.md5(admin.getPassword())));
        } else {
            admin.setPassword(existingAdmin.getPassword());
        }
        
        admin.setId(id);
        admin.setCreateTime(existingAdmin.getCreateTime());
        admin.setStatus(existingAdmin.getStatus());
        systemAdminRepository.save(admin);
        return SaResult.ok("更新成功");
    }

    @DeleteMapping("{id}")
    public SaResult delete(@PathVariable Integer id) {
        // StpUtil.checkPermission("sys:admin:delete");
        if (id == 0) {
            return SaResult.error("超级管理员不能删除");
        }
        systemAdminRepository.deleteById(id);
        return SaResult.ok("删除成功");
    }

}
